import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_drag_scale_widget/flutter_drag_scale_widget.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:flutter_learn_vi/src/page/common/common_nodata_widget.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';
import 'package:get/get.dart';
import 'package:get/state_manager.dart';

import '../../bean/bean_study_data.dart';
import '../../bean/bean_video.dart';
import '../../utils/navigator_utils.dart';
import '../common/common_pdf_page.dart';
import 'controller/study_data_details_controller.dart';
import 'course/video_details2_widget.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2021/1/13.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
///代码清单
class StudyDataDatilsPage extends StatefulWidget {
  final int id;

  const StudyDataDatilsPage({Key key, this.id}) : super(key: key);

  @override
  _StudyDataPageState createState() => _StudyDataPageState();
}

///当前页面被装载在[PageView]中，使用KeepAlive使用页面保持状态
class _StudyDataPageState extends State<StudyDataDatilsPage>
    with SingleTickerProviderStateMixin {
  @override
  void initState() {
    super.initState();
    Get.put(MyStudyDataDetailsController());
    Future.delayed(Duration.zero, () {
      Get.find<MyStudyDataDetailsController>().onPullRefresh(widget.id);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("资料详情"),
      ),
      body: SizedBox(
        width: double.infinity,
        height: double.infinity,
        child: GetBuilder(
          id: "details",
          builder: (MyStudyDataDetailsController controller) {
            return buildManiWidget(controller);
          },
        ),
      ),
    );
  }

  buildManiWidget(MyStudyDataDetailsController controller) {
    if (controller.isLoading) {
      return LoadingWidget();
    }
    StudyDataBean studyDataBean = controller.studyDataBean;
    if (studyDataBean == null) {
      return NoDataWidget(
        clickCallBack: () {
          Get.find<MyStudyDataDetailsController>()
              .onClickItemRefresh(widget.id);
        },
      );
    }
    return buildListWidget(controller);
  }

  buildListWidget(MyStudyDataDetailsController controller) {
    StudyDataBean studyDataBean = controller.studyDataBean;
    List<StudyItemDataBean> itemList = controller.studyDataBean.itemList;
    return RefreshIndicator(
      notificationPredicate: (ScrollNotification notifation) {
        //该属性包含当前ViewPort及滚动位置等信息
        ScrollMetrics scrollMetrics = notifation.metrics;
        if (scrollMetrics.minScrollExtent == 0) {
          return true;
        } else {
          return false;
        }
      },
      onRefresh: () async {
        return Get.find<MyStudyDataDetailsController>()
            .onClickItemRefresh(widget.id);
      },
      child: NestedScrollView(
        body: ListView.builder(
          itemCount: itemList.length,
          itemBuilder: (BuildContext context, int index) {
            StudyItemDataBean item = itemList[index];

            return Container(
              color: Colors.white,
              padding: EdgeInsets.only(left: 12, right: 12, bottom: 10),
              child: InkWell(
                onTap: () {},
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Container(
                          width: 22,
                          height: 22,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              border: Border.all(color: Colors.grey),
                              borderRadius:
                                  BorderRadius.all(Radius.circular(2))),
                          child: Text(
                            "${index + 1}",
                            style: TextStyle(
                                fontWeight: FontWeight.w600, fontSize: 12),
                          ),
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        Expanded(
                          child: Text(
                            item.materialContent,
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(fontSize: 14, color: Colors.black),
                          ),
                        ),
                      ],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        TextButton(
                          onPressed: () {
                            Clipboard.setData(
                                ClipboardData(text: item.materialContent));
                            ToastUtils.showToast("已复制链接到剪切板");
                          },
                          child: Text("复制链接"),
                        ),
                        TextButton(
                          onPressed: () {
                            if (studyDataBean.videoTypes == 6) {
                              //查看图片
                              List<String> imageList = [];
                              List<StudyItemDataBean> itemList =
                                  studyDataBean.itemList;
                              itemList.forEach((element) {
                                imageList.add(element.materialContent);
                              });
                              NavigatorUtils.pushPage(
                                context,
                                ImageScanPage(
                                  imageList: imageList,
                                ),
                              );
                              return;
                            }
                            if (studyDataBean.videoTypes == 3) {
                              //查看视频
                              List<String> imageList = [];
                              List<StudyItemDataBean> itemList =
                                  studyDataBean.itemList;
                              itemList.forEach((element) {
                                imageList.add(element.materialContent);
                              });
                              NavigatorUtils.pushPage(
                                context,
                                VideoScanPage(
                                  videoList: imageList,
                                ),
                              );
                              return;
                            }
                            NavigatorUtils.pushPage(
                              context,
                              PdfWidgetPage(
                                showTitle: true,
                                title: studyDataBean.videoName,
                                url: item.materialContent,
                                isPdf: false,
                              ),
                            );
                          },
                          child: Text("查看详情"),
                        ),
                        SizedBox(
                          height: 8,
                        ),
                      ],
                    )
                  ],
                ),
              ),
            );
          },
        ),
        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
          int type = studyDataBean.videoTypes;
          String typeStr = "-";
          Color textColor = Colors.grey;
          if (type == 0) {
            typeStr = "PPT";
            textColor = Colors.deepOrange;
          } else if (type == 1) {
            typeStr = "Word";
            textColor = Colors.blue;
          } else if (type == 2) {
            typeStr = "Excel";
            textColor = Colors.green;
          } else if (type == 3) {
            typeStr = "视频";
            textColor = Colors.grey;
          } else if (type == 4) {
            typeStr = "PDF";
            textColor = Colors.grey;
          } else if (type == 5) {
            typeStr = "txt";
            textColor = Colors.grey;
          } else if (type == 6) {
            typeStr = "图片";
            textColor = Colors.grey;
          } else {
            typeStr = "其他";
            textColor = Colors.grey;
          }
          return [
            SliverToBoxAdapter(
              child: Container(
                color: Colors.white,
                padding: EdgeInsets.all(12),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Row(
                      children: [
                        Container(
                          width: 4,
                          height: 18,
                          decoration: BoxDecoration(
                              color: Colors.green,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(4))),
                          margin: EdgeInsets.only(right: 10),
                        ),
                        Expanded(
                            child: Text(
                          "${studyDataBean.videoName}",
                          style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.w500,
                              color: Colors.black),
                        )),
                      ],
                    ),
                    Row(
                      children: [
                        Container(
                          margin: EdgeInsets.only(top: 8, left: 14),
                          child: Text(
                            "资料数量 ${studyDataBean.materialNumber} 份",
                            style: TextStyle(
                                fontSize: 14,
                                fontWeight: FontWeight.w400,
                                color: Colors.black),
                          ),
                        ),
                        Container(
                          padding: EdgeInsets.only(
                              left: 8, right: 8, top: 3, bottom: 3),
                          margin: EdgeInsets.only(top: 8, left: 14),
                          decoration: BoxDecoration(
                              color: textColor,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(4))),
                          child: Text(
                            "$typeStr",
                            style: TextStyle(
                                fontSize: 14,
                                fontWeight: FontWeight.w500,
                                color: Colors.white),
                          ),
                        ),
                      ],
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 8, left: 14),
                      child: Text(
                        "${studyDataBean.videoInfo}",
                        style: TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.w400,
                            color: Colors.black),
                      ),
                    )
                  ],
                ),
              ),
            )
          ];
        },
      ),
    );
  }
}

class ImageScanPage extends StatelessWidget {
  final List<String> imageList;

  const ImageScanPage({Key key, this.imageList}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('图片浏览'),
      ),
      body: ImageShowPageView(
        //图片数据
        imageList: imageList,
        //图片的类型
        imageShowType: ImageShowType.NET,
        //图片的填充方式
        boxFit: BoxFit.contain,
        onPageChanged: (int index) {},
      ),
    );
  }
}

class VideoScanPage extends StatefulWidget {
  final List<String> videoList;

  const VideoScanPage({Key key, this.videoList}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _VideoScanPageState();
  }
}

class _VideoScanPageState extends State<VideoScanPage> {
  VideoModel _videoModel;

  @override
  void initState() {
    super.initState();
    _videoModel = new VideoModel();
    _videoModel.videoUrl = widget.videoList[0];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('视频浏览'),
      ),
      body: Center(
        child: Container(
          height: 240,
          child: VideoDetailsWidget(
            init: _videoModel,
            key: UniqueKey(),
          ),
        ),
      ),
    );
  }
}
